#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int i, j, left, right;
        sort(nums.begin(), nums.end());
        int size = nums.size();

        vector<vector<int>> vv;
        if (size < 4)
            return vv;
        for (i = 0; i < size - 3;) {


            for (j = i + 1; j < size - 2;) {

                long int x = (long)target - nums[i] - nums[j];
                left = j + 1, right = size - 1;

                while (left < right) {
                    if (nums[left] + nums[right] > x) {
                        right--;
                    }
                    else if (nums[left] + nums[right] < x) {
                        left++;

                    }
                    else {
                        vv.push_back(
                            { nums[i], nums[j], nums[left], nums[right] });
                        left++, right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }
                j++;
                while (j < size - 2 && nums[j] == nums[j - 1]) {
                    j++;
                }
            }
            i++;
            while (i < size - 3 && nums[i] == nums[i - 1]) {
                i++;
            }
        }
        return vv;
    }
};